//获取应用实例
const app = getApp()
import api from '../../utils/api'

Page({
  data: {
    cartList: [],
    zcList: [],
    wcList: [],
    ycList: [],
    empty: false,
    total: 0,
    switchFlag: false,
    zcChecked: true,
    wcChecked: true,
    ycChecked: true,
  },
  onLoad: function(options) {
    this.updCartList();
  },
  onReady: function() {
    // Do something when page ready.
  },
  onShow: function() {
    // Do something when page show.
  },
  onHide: function() {
    // Do something when page hide.
  },
  onUnload: function() {
    // Do something when page close.
  },
  onPullDownRefresh: function() {
    // Do something when pull down.
  },
  onReachBottom: function() {
    // Do something when page reach bottom.
  },
  onShareAppMessage: function() {
    // return custom share data when user share.
  },
  onPageScroll: function() {
    // Do something when page scroll
  },
  // 全选
  selectAll: function(e) {
    let that = this;
    let check = false;
    if (e.detail.value == '') {
      check = false
    } else {
      check = true;
    }
    let cb = e.currentTarget.dataset.cb;
    if (cb == 1) {
      let zcList = that.data.zcList;
      zcList.filter(item => {
        item.checked = check;
      })
      that.setData({
        zcList: zcList
      })
    }
    if (cb == 2) {
      let wcList = that.data.wcList;
      wcList.filter(item => {
        item.checked = check;
      })
      that.setData({
        wcList: wcList
      })
    }
    if (cb == 3) {
      let ycList = that.data.ycList;
      ycList.filter(item => {
        item.checked = check;
      })
      that.setData({
        ycList: ycList
      })
    }
    this.total();
  },
  switchChange(e) {
    this.setData({
      switchFlag: e.detail.value
    })
  },
  onTabItemTap(item) {
    console.log(item.index)
    console.log(item.pagePath)
    console.log(item.text)
  },
  category: function(list) {
    let zcList = this.data.zcList;
    let wcList = this.data.wcList;
    let ycList = this.data.ycList;
    for (let i = 0; i < list.length; i++) {
      if (list[i].meals == "早餐") {
        zcList.push(list[i]);
      }
      if (list[i].meals == "午餐") {
        wcList.push(list[i]);
      }
      if (list[i].meals == "晚餐") {
        ycList.push(list[i]);
      }
    }
    this.setData({
      zcList: zcList,
      wcList: wcList,
      ycList: ycList
    })
  },
  isExist(item) {
    let cartList = app.globalData.cartGoods;
    let flag = false;
    cartList.filter(row => {
      if (row.id == item.id && row.sfxf == 'y') {
        flag = true;
      }
    })
    return flag;
  },
  updCartList() { // 更新购物列表
    let cartList = app.globalData.cartGoods;
    let cartHalfGoods = app.globalData.cartHalfGoods;

    // 判断购物车为空
    if (cartList.length == 0 && cartHalfGoods.length == 0) {
      this.setData({
        empty: true
      });
      return;
    }
    this.category(cartList);
    this.category(cartHalfGoods);

    this.total();
  },
  checkboxChange: function(e) {
    const _this = this;
    let listIndex = e.currentTarget.dataset.listindex;
    let cb = e.currentTarget.dataset.cb;
    if (cb == 1) {
      if (e.detail.value == '') {
        _this.data.zcList[listIndex].checked = false;
      } else {
        _this.data.zcList[listIndex].checked = true;
      }

      let zcChecked = true;
      let zcList = _this.data.zcList;
      for (let i = 0; i < zcList.length; i++) {
        if (!zcList[i].checked) {
          zcChecked = false;
          break;
        }
      }
      _this.setData({
        zcChecked: zcChecked
      })
    }
    if (cb == 2) {
      if (e.detail.value == '') {
        _this.data.wcList[listIndex].checked = false;
      } else {
        _this.data.wcList[listIndex].checked = true;
      }

      let wcChecked = true;
      let wcList = _this.data.wcList;
      for (let i = 0; i < wcList.length; i++) {
        if (!wcList[i].checked) {
          wcChecked = false;
          break;
        }
      }
      _this.setData({
        wcChecked: wcChecked
      })
    }
    if (cb == 3) {
      if (e.detail.value == '') {
        _this.data.ycList[listIndex].checked = false;
      } else {
        _this.data.ycList[listIndex].checked = true;
      }

      let ycChecked = true;
      let ycList = _this.data.ycList;
      for (let i = 0; i < ycList.length; i++) {
        if (!ycList[i].checked) {
          ycChecked = false;
          break;
        }
      }
      _this.setData({
        ycChecked: ycChecked
      })
    }

    this.total();
  },
  total() {
    let cartList = [];
    let totalPrice = 0;
    this.data.zcList.forEach((k, v) => {
      if (k.checked) {
        totalPrice += k.num * k.price;
        cartList.push(k);
      }
    })
    this.data.wcList.forEach((k, v) => {
      if (k.checked) {
        totalPrice += k.num * k.price;
        cartList.push(k);
      }
    })
    this.data.ycList.forEach((k, v) => {
      if (k.checked) {
        totalPrice += k.num * k.price;
        cartList.push(k);
      }
    })
    this.setData({
      total: totalPrice,
      cartList: cartList
    });
  },
  actioncnt() {
    const _this = this;
    if (this.data.total == 0) {
      wx.showToast({
        icon: 'none',
        title: '请选择商品',
      })
      return;
    }

    wx.showModal({
      title: '提示',
      content: '您订的是明天的饭哦，确定支付吗？',
      success: function (sm) {
        if (sm.confirm) {
          _this.submitOrder();
        }
      }
    })

    // wx.showActionSheet({
    //   itemList: ['账户余额', '您订的是明天的饭哦，确定支付吗？'],
    //   success: function(res) {
    //     if (res.tapIndex == 0) {
    //       _this.submitOrder();
    //     } else {
    //       return;
    //       // wx.showToast({
    //       //   icon: 'none',
    //       //   title: '暂未开通',
    //       // })
    //     }
    //   },
    //   fail: function(res) {
    //     console.log(res.errMsg)
    //   }
    // })
  },
  updUser() {
    let user = wx.getStorageSync("user");
    let param = {
      "patientId": user.bh
    };
    api.POST({
      url: 'login.action',
      params: param,
      success: function(res) {
        let success = res.data.success;
        if (success == "true") {
          let user = res.data.data[0]; //replace(/\s+/g, '')
          user.bh = user.bh.replace(/\s+/g, '');
          wx.setStorage({
            key: 'user',
            data: user
          })
        } else {
          wx.showToast({
            icon: 'none',
            title: res.data.msg,
            duration: 5000
          })
        }
      },
      fail: function() {
        wx.showToast({
          icon: 'none',
          title: '请求失败',
          duration: 5000
        })
      },
    })

  },
  submitOrder() {
    let user = wx.getStorageSync("user");
    let province = app.globalData.province;
    let city = app.globalData.city;
    let district = app.globalData.district;
    let street = app.globalData.street;
    let street_number = app.globalData.street_number;
    let latitude = app.globalData.latitude;
    let longitude = app.globalData.longitude;
    let _this = this;
    let list = [];
    this.data.cartList.forEach((k, v) => {
      if (k.checked) {
        let recipe = {
          "dailyId": k.id,
          "number": k.num,
          "patientId": user.bh,
          "paymentSource": "account",
          "halfPart": k.sfxf,
          "province": province,
          "city": city,
          "district": district,
          "street": street,
          "streetNumber": street_number,
          "latitude": latitude,
          "longitude": longitude,
        };
        list.push(recipe);
      }
    })
    let param = {
      "patientId": user.bh,
      "paymentSource": "account",
      "recipes": list
    }
    api.POST({
      url: 'submitOrder.action',
      params: param,
      success: function(res) {
        if (res.data.success == "true") {
          _this.clearCartList();
          _this.updUser();
          wx.showModal({
            title: '提示',
            content: '支付成功',
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                // console.log('用户点击确定')
              } else {
                // console.log('用户点击取消')
              }

            }
          })
        } else {
          // wx.showToast({
          //   icon: 'none',
          //   title: res.data.msg,
          // })
          wx.showModal({
            title: '提示',
            content: res.data.msg,
            showCancel: false,
            success: function(res) {
              if (res.confirm) {
                console.log('用户点击确定')
              } else {
                console.log('用户点击取消')
              }

            }
          })
        }

      },
      fail: function() {
        wx.showToast({
          icon: 'none',
          title: '提交失败',
        })
      },
    })
  },
  clearCartList() {
    let goods = app.globalData.stoves;
    let cartList = app.globalData.cartGoods;
    let cartHalfGoods = app.globalData.cartHalfGoods;
    let empty = true;
    let {
      zcList,
      wcList,
      ycList
    } = this.data;

    for (var m = 0; m < zcList.length; m++) {
      if (zcList[m].checked) {
        let food = zcList[m];
        var tabIndex = food.tabIndex;
        var mealIndex = food.mealIndex;
        var foodIndex = food.foodIndex;
        if (food.half_state == 'N') {
          goods[tabIndex].meals[mealIndex].recipes[foodIndex].Count = 0;
          for (var i = 0; i < cartList.length; i++) {
            if (cartList[i].id == zcList[m].id) {
              cartList.splice(i--, 1);
            }
          }
        } else {
          if (food.sfxf == 'n') {
            let countSum = goods[tabIndex].meals[mealIndex].recipes[foodIndex].countSum;
            let count = goods[tabIndex].meals[mealIndex].recipes[foodIndex].count;
            goods[tabIndex].meals[mealIndex].recipes[foodIndex].countSum = countSum - count;
            goods[tabIndex].meals[mealIndex].recipes[foodIndex].count = 0;
            for (var i = 0; i < cartList.length; i++) {
              if (cartList[i].id == zcList[m].id) {
                cartList.splice(i--, 1);
              }
            }
          }
          if (food.sfxf == 'y') {
            goods[tabIndex].meals[mealIndex].recipes[foodIndex].countSum--;
            goods[tabIndex].meals[mealIndex].recipes[foodIndex].xfCount--;
            for (var i = 0; i < cartHalfGoods.length; i++) {
              if (cartHalfGoods[i].id == zcList[m].id) {
                cartHalfGoods.splice(i--, 1);
              }
            }
          }
        }
        zcList.splice(m--, 1);
      }
    }
    for (var m = 0; m < wcList.length; m++) {
      if (wcList[m].checked) {
        let food = wcList[m];
        var tabIndex = food.tabIndex;
        var mealIndex = food.mealIndex;
        var foodIndex = food.foodIndex;
        if (food.half_state == 'N') {
          goods[tabIndex].meals[mealIndex].recipes[foodIndex].Count = 0;
          for (var i = 0; i < cartList.length; i++) {
            if (cartList[i].id == wcList[m].id) {
              cartList.splice(i--, 1);
            }
          }
        } else {
          if (food.sfxf == 'n') {
            let countSum = goods[tabIndex].meals[mealIndex].recipes[foodIndex].countSum;
            let count = goods[tabIndex].meals[mealIndex].recipes[foodIndex].count;
            goods[tabIndex].meals[mealIndex].recipes[foodIndex].countSum = countSum - count;
            goods[tabIndex].meals[mealIndex].recipes[foodIndex].count = 0;
            for (var i = 0; i < cartList.length; i++) {
              if (cartList[i].id == wcList[m].id) {
                cartList.splice(i--, 1);
              }
            }
          }
          if (food.sfxf == 'y') {
            goods[tabIndex].meals[mealIndex].recipes[foodIndex].countSum--;
            goods[tabIndex].meals[mealIndex].recipes[foodIndex].xfCount--;
            for (var i = 0; i < cartHalfGoods.length; i++) {
              if (cartHalfGoods[i].id == wcList[m].id) {
                cartHalfGoods.splice(i--, 1);
              }
            }
          }
        }
        wcList.splice(m--, 1);
      }
    }
    for (var m = 0; m < ycList.length; m++) {
      if (ycList[m].checked) {
        let food = ycList[m];
        var tabIndex = food.tabIndex;
        var mealIndex = food.mealIndex;
        var foodIndex = food.foodIndex;
        if (food.half_state == 'N') {
          goods[tabIndex].meals[mealIndex].recipes[foodIndex].Count = 0;
          for (var i = 0; i < cartList.length; i++) {
            if (cartList[i].id == ycList[m].id) {
              cartList.splice(i--, 1);
            }
          }
        } else {
          if (food.sfxf == 'n') {
            let countSum = goods[tabIndex].meals[mealIndex].recipes[foodIndex].countSum;
            let count = goods[tabIndex].meals[mealIndex].recipes[foodIndex].count;
            goods[tabIndex].meals[mealIndex].recipes[foodIndex].countSum = countSum - count;
            goods[tabIndex].meals[mealIndex].recipes[foodIndex].count = 0;
            for (var i = 0; i < cartList.length; i++) {
              if (cartList[i].id == ycList[m].id) {
                cartList.splice(i--, 1);
              }
            }
          }
          if (food.sfxf == 'y') {
            goods[tabIndex].meals[mealIndex].recipes[foodIndex].countSum--;
            goods[tabIndex].meals[mealIndex].recipes[foodIndex].xfCount--;
            for (var i = 0; i < cartHalfGoods.length; i++) {
              if (cartHalfGoods[i].id == ycList[m].id) {
                cartHalfGoods.splice(i--, 1);
              }
            }
          }
        }
        ycList.splice(m--, 1);
      }
    }
    if (zcList.length > 0) {
      empty = false;
    }
    if (wcList.length > 0) {
      empty = false;
    }
    if (ycList.length > 0) {
      empty = false;
    }
    this.setData({
      cartList: [],
      zcList: zcList,
      wcList: wcList,
      ycList: ycList,
      empty: empty,
      total: 0
    });
    app.globalData.cartGoods = cartList;
    app.globalData.cartHalfGoods = cartHalfGoods;
    app.globalData.stoves = goods;
  },
  delCart() {
    let _this = this;
    if (this.data.total <= 0){
      wx.showToast({
        title: '请选择数据!',
        duration: 1000,
      })
      return;
    }
    wx.showModal({
      title: '提示',
      content: '确认删除吗？',
      success: function(res) {
        if (res.confirm) {
          _this.clearCartList();
        }

      }
    })
    
  }
})